import Taro from '@tarojs/taro';
import { Authientication } from '@doctorwork/utils';

import api, { appId, appName } from '../api';


const options = {
    loginPage: '/pages/login/index',
    authPage: '/sso/passport/login_miniapp',
    withProfile: 1,
    webRedirectPage: '/base/_login/index',
    webAuthPage: api.WEAPP_SSOSEVER_API + '/passport/auth_wx',
    appId,
    appName,
    sso: api.WEAPP_SSOSEVER_API
};

export const handler = new Authientication(options);

export default {
    namespace: '$error',
    state: { authTime: '' },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *auth({ payload }, { put, select }) {
            // 防止短时间内重复登录
            let timestamp = new Date().getTime();
            // 访问内存
            const authTime = yield select(state => state.$error.authTime);
            if (authTime && timestamp - authTime < 15000) {
                return false;
            }
            yield put({
                type: 'save',
                payload: {
                    authTime: timestamp
                }
            });
            return yield handler.auth();

        },
        *other({ payload }) {
            const { errmsg , msg } = payload;
            setTimeout(function () {
                Taro.showToast({
                    title: errmsg || msg || '系统异常',
                    icon: 'none',
                    duration: 2000
                }).then(res => console.log(res));
            }, 1000);

        }
    }
};
